package com.lx.service;

import com.lx.dao.BookDao;
import com.lx.dao.UserDao;
import com.lx.entity.Book;
import com.lx.entity.User;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.List;

@Service
public class BookService {
    @Autowired
    private BookDao bookDao;
    @Autowired
    private UserDao userDao;

    //查询所有图书
    public List<Book> getBook(int page, int pageSize) {
        List<Book> books = bookDao.getBook((page - 1) * pageSize, pageSize);
        for (Book book : books) {
            if (book.getUser_id() != 0){//已借阅
                //借阅的用户名
                String user_name = userDao.getUserById(book.getUser_id()).getUser_name();
                book.setUser_name(user_name);
            }else { //未借阅
                book.setUser_name("未借阅");
            }
        }
        return books;
    }

    //通过图书名称进行模糊查询
    public List<Book> getBookByNameLike(String book_name){
        return bookDao.getBookByNameLike(book_name);
    }
    //通过id查询图书
    public Book getBookById(int id){
        return bookDao.getBookById(id);
    }

    //查询所有图书数量
    public int countBook() {
        return bookDao.countBook().size();
    }

    //添加图书
    public Book addBook(String book_name, String book_author, String book_time,
                           String book_content, String book_type){
        //查询书名是否注册
        Book bookByName = bookDao.getBookByName(book_name);
        if (bookByName == null){//未注册
            bookDao.addBook(book_name,book_author,book_time,book_content,book_type);
            return bookDao.getBookByName(book_name);
        }else {
            return null;
        }
    }

    //删除
    public boolean deleteBook(int id){
        return bookDao.deleteBook(id);
    }

    //修改
    public boolean updateBook(Book book){
        return bookDao.updateBook(book);
    }

    //借阅图书
    public boolean myBook(int user_id,int book_id){
        return bookDao.updateBookUserId(user_id, book_id);
    }
    //归还图书
    public boolean noMyBook(int book_id){
        return bookDao.updateBookUserId(0, book_id);
    }
}
